//
//  GameScene.m
//  PlaneWar2
//
//  Created by HappyMilk 02 on 2017/3/28.
//  Copyright © 2017年 HappyMilk 02. All rights reserved.
//

#import "GameScene.h"
#import "GameOverScene.h"


typedef NS_ENUM(uint32_t, PhysicsCategory) {
    PhysicsNone = 0,
    PhysicsPlanOne = 1,
    PhysicsPlanTwo = 2,
    PhysicsPlanThree = 3,
    PhysicsPlanFour = 4,
    PhysicsPlanFive = 5,
    PhysicsBullet = 6
};

@interface GameScene ()<SKPhysicsContactDelegate>

@property (nonatomic) BOOL isOver;

@property (nonatomic) CGPoint firstPoint;

@end

@implementation GameScene {
    
    SKSpriteNode *zhadan;
    SKSpriteNode *background;
    SKLabelNode *gradesLb;
    NSInteger _grades;
    
    SKAction *_fashe;
    SKAction *_baofa;
}

- (CGFloat )random{
    return (CGFloat)((CGFloat)arc4random() / 0xFFFFFFFF);
}
- (CGFloat )randomeBy:(CGFloat )min and:(CGFloat )max{
    return [self random] * (max - min) + min;
}

- (void)didMoveToView:(SKView *)view {
    
    _fashe = [SKAction playSoundFileNamed:@"sound_fa.mp3" waitForCompletion:NO];
    _baofa = [SKAction playSoundFileNamed:@"sound_bao.wav" waitForCompletion:NO];
    
    _firstPoint = (CGPoint){0,10};
    _isOver = NO;_grades = 10;
    // Setup your scene here
    self.backgroundColor = [SKColor whiteColor];
    // Get label node from scene and store it for use later
    [self loadBackground];
    [self addGradesNode];
    
    zhadan = [SKSpriteNode spriteNodeWithImageNamed:@"dapao"];
    zhadan.position = (CGPoint){self.size.width/2 ,30};
    zhadan.size = CGSizeMake(40, 60);
    zhadan.zPosition = 99;
    [self addChild:zhadan];
    
    self.physicsWorld.gravity = (CGVector){0,0};
    self.physicsWorld.contactDelegate = self;
    
    [self runAction:[SKAction repeatActionForever:[SKAction sequence:@[[SKAction runBlock:^{
        [self addCloudsNode];
    }],[SKAction waitForDuration:4.0]]]]];
    
    
    
    //
    if (self.gameType == 1) {
        [self runAction:[SKAction repeatActionForever:[SKAction sequence:@[[SKAction runBlock:^{
            CGFloat num = [self random];
            if (num < 0.3) {
                [self addPlaneNodeTwo];
            }else{
                [self addPlaneNodeOne];
            }
        }],[SKAction waitForDuration:1.0]]]]];
    }else if (self.gameType == 2){
        [self runAction:[SKAction repeatActionForever:[SKAction sequence:@[[SKAction runBlock:^{
            CGFloat num = [self random];
            if (num < 0.6 ) {
                [self addPlaneNodeTwo];
            }else {
                [self addPlaneNodeOne];
            }
        }],[SKAction waitForDuration:1.0]]]]];
    }else if (self.gameType == 3){
        [self runAction:[SKAction repeatActionForever:[SKAction sequence:@[[SKAction runBlock:^{
            CGFloat num = [self random];
            if (num<0.5) {
                [self addPlaneNodeTwo];
            }else if (num>0.8){
                [self addPlaneNodeThree];
            }else{
                [self addPlaneNodeOne];
            }
        }],[SKAction waitForDuration:1.0]]]]];
    }else if (self.gameType == 4){
        [self runAction:[SKAction repeatActionForever:[SKAction sequence:@[[SKAction runBlock:^{
            CGFloat num = [self random];
            if (num<0.5) {
                [self addPlaneNodeTwo];
            }else if (0.5<num<0.7){
                [self addPlaneNodeOne];
            }else if (0.7<num<0.9){
                [self addPlaneNodeThree];
            }else{
                [self addPlaneNodeFour];
            }
        }],[SKAction waitForDuration:0.8]]]]];
    }else{
        [self runAction:[SKAction repeatActionForever:[SKAction sequence:@[[SKAction runBlock:^{
            CGFloat num = [self random];
            if (num<0.5) {
                [self addPlaneNodeTwo];
            }else if (0.5<num<0.7){
                [self addPlaneNodeOne];
            }else if (0.7<num<0.8){
                [self addPlaneNodeThree];
            }else if (0.8<num<0.9){
                [self addPlaneNodeFour];
            }else{
                [self addPlaneNodeFive];
            }
        }],[SKAction waitForDuration:0.5]]]]];
    }
    
    
    [self runAction:[SKAction repeatActionForever:[SKAction sequence:@[[SKAction runBlock:^{
        [self changeGrades:-1];
    }],[SKAction waitForDuration:1]]]]];
    
}

- (void)addGradesNode{
    
    gradesLb = [SKLabelNode labelNodeWithText:@"Grades: 0"];
    gradesLb.zPosition = 100;
    gradesLb.position = CGPointMake(self.size.width/2, self.size.height-30);
    gradesLb.fontSize = 18;
    gradesLb.fontName = @"Bold";
    gradesLb.fontColor = [SKColor redColor];
    [self addChild:gradesLb];
}
- (void)changeGrades:(NSInteger)grades{
    
    _grades = _grades + grades;
    if (_grades >= 100) {
        
        [self removeAllActions];
        [self removeAllChildren];
        _isOver = YES;
        [self gameWin];
        
    }else if (_grades > 0 && _grades<100){
        NSString *str = [NSString stringWithFormat:@"Grades: %ld",_grades];
        gradesLb.text = str;
    }else{
        
        [self removeAllActions];
        [self removeAllChildren];
        _isOver = YES;
        [self gameOver];
    }
    
}

- (void)loadBackground{
    
    SKTexture *texture = [SKTexture textureWithImage:[UIImage imageNamed:@"background"]];
    background = [SKSpriteNode spriteNodeWithTexture:texture size:self.size];
    background.position = CGPointMake(self.size.width/2, self.size.height/2);
    background.zPosition = 0;
    [self addChild:background];
}
- (void)addCloudsNode{

    SKSpriteNode *cloud = [SKSpriteNode spriteNodeWithImageNamed:@"yun"];
    cloud.position = CGPointMake(self.size.width*[self random], self.size.height);
    
    [self addChild:cloud];
    
    SKAction *move = [SKAction moveToY:0.0 duration:20];
    SKAction *moveDone = [SKAction removeFromParent];
    [cloud runAction:[SKAction sequence:@[move,moveDone]]];
}

- (void)addPlaneNodeOne{

    SKSpriteNode *plane = [SKSpriteNode spriteNodeWithImageNamed:@"plane1"];
    plane.position = CGPointMake(self.size.width*[self random], self.size.height);
    [self addChild:plane];
    
    plane.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:plane.size.width/2];
    plane.physicsBody.dynamic = YES;
    plane.physicsBody.categoryBitMask = PhysicsPlanOne;
    plane.physicsBody.contactTestBitMask = PhysicsBullet;
    plane.physicsBody.collisionBitMask = PhysicsNone;
    
    CGFloat moveTime = [self randomeBy:2.0 and:4.0];
    SKAction *move = [SKAction moveToY:0.0 duration:moveTime];
    SKAction *moveDone = [SKAction removeFromParent];
    [plane runAction:[SKAction sequence:@[move,moveDone]]];
}

- (void)addPlaneNodeTwo{

    SKSpriteNode *plane = [SKSpriteNode spriteNodeWithImageNamed:@"plane2"];
    plane.position = CGPointMake(self.size.width*[self random], self.size.height);
    [self addChild:plane];
    
    plane.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:plane.size.width/2];
    plane.physicsBody.dynamic = YES;
    plane.physicsBody.categoryBitMask = PhysicsPlanTwo;
    plane.physicsBody.contactTestBitMask = PhysicsBullet;
    plane.physicsBody.collisionBitMask = PhysicsNone;
    
    CGFloat moveTime = [self randomeBy:1.0 and:5.0];
    SKAction *move = [SKAction moveToY:0.0 duration:moveTime];
    SKAction *moveDone = [SKAction removeFromParent];
    [plane runAction:[SKAction sequence:@[move,moveDone]]];
}

- (void)addPlaneNodeThree{
    
    SKSpriteNode *plane = [SKSpriteNode spriteNodeWithImageNamed:@"plane3"];
    plane.position = CGPointMake(self.size.width*[self random], self.size.height);
    [self addChild:plane];
    
    plane.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:plane.size.width/2];
    plane.physicsBody.dynamic = YES;
    plane.physicsBody.categoryBitMask = PhysicsPlanThree;
    plane.physicsBody.contactTestBitMask = PhysicsBullet;
    plane.physicsBody.collisionBitMask = PhysicsNone;
    
    CGFloat moveTime = [self randomeBy:1.0 and:4.0];
    SKAction *move = [SKAction moveToY:0.0 duration:moveTime];
    SKAction *moveDone = [SKAction removeFromParent];
    [plane runAction:[SKAction sequence:@[move,moveDone]]];
}
- (void)addPlaneNodeFour{
    
    SKSpriteNode *plane = [SKSpriteNode spriteNodeWithImageNamed:@"plane4"];
    plane.position = CGPointMake(self.size.width*[self random], self.size.height);
    [self addChild:plane];
    
    plane.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:plane.size.width/2];
    plane.physicsBody.dynamic = YES;
    plane.physicsBody.categoryBitMask = PhysicsPlanFour;
    plane.physicsBody.contactTestBitMask = PhysicsBullet;
    plane.physicsBody.collisionBitMask = PhysicsNone;
    
    CGFloat moveTime = [self randomeBy:1.0 and:3.0];
    SKAction *move = [SKAction moveToY:0.0 duration:moveTime];
    SKAction *moveDone = [SKAction removeFromParent];
    [plane runAction:[SKAction sequence:@[move,moveDone]]];
}
- (void)addPlaneNodeFive{
    
    SKSpriteNode *plane = [SKSpriteNode spriteNodeWithImageNamed:@"plane5"];
    plane.position = CGPointMake(self.size.width*[self random], self.size.height);
    [self addChild:plane];
    
    plane.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:plane.size.width/2];
    plane.physicsBody.dynamic = YES;
    plane.physicsBody.categoryBitMask = PhysicsPlanFive;
    plane.physicsBody.contactTestBitMask = PhysicsBullet;
    plane.physicsBody.collisionBitMask = PhysicsNone;
    
    //CGFloat moveTime = [self randomeBy:2.0 and:4.0];
    SKAction *move = [SKAction moveToY:0.0 duration:1.5];
    SKAction *moveDone = [SKAction removeFromParent];
    [plane runAction:[SKAction sequence:@[move,moveDone]]];
}
- (void)addBulletNodeBy:(CGPoint)location{

    SKSpriteNode *bullet = [SKSpriteNode spriteNodeWithImageNamed:@"zhadan"];
    bullet.position = CGPointMake(zhadan.position.x, zhadan.position.y+20);
    [self addChild:bullet];
    
    bullet.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:bullet.size.width/2];
    bullet.physicsBody.dynamic = YES;
    bullet.physicsBody.categoryBitMask = PhysicsBullet;
    bullet.physicsBody.contactTestBitMask = PhysicsPlanOne;
    bullet.physicsBody.collisionBitMask = PhysicsNone;
    
    CGFloat move_x = self.size.height/location.y*(location.x-self.size.width/2)+self.size.width/2;
    CGFloat time = sqrtf(self.size.height*self.size.height + move_x*move_x)/self.size.height;
    SKAction *move = [SKAction moveTo:CGPointMake(move_x, self.size.height) duration:time];
    SKAction *roten = [SKAction rotateByAngle:15 duration:1];
    SKAction *moveDone = [SKAction removeFromParent];
    [bullet runAction:[SKAction repeatActionForever:roten]];
    [bullet runAction:[SKAction sequence:@[move,moveDone]]];
}

- (void)gameWin{
    
    [self addGradesNode];
    
    SKTexture *texture = [SKTexture textureWithImage:[UIImage imageNamed:@"paper_background"]];
    SKSpriteNode *background1 = [SKSpriteNode spriteNodeWithTexture:texture size:self.size];
    background1.position = CGPointMake(self.size.width/2, self.size.height/2);
    background1.zPosition = 0;
    [self addChild:background1];
    
    SKSpriteNode *alert = [SKSpriteNode spriteNodeWithImageNamed:@"win"];
    alert.position = CGPointMake(self.size.width/2, self.size.height/2);
    [self addChild:alert];
    
    SKSpriteNode *menu = [SKSpriteNode spriteNodeWithImageNamed:@"btn_blue"];
    menu.position = CGPointMake(self.size.width/2, self.size.height/2+10);
    menu.name = @"menu";
    [self addChild:menu];
    
    SKSpriteNode *agin = [SKSpriteNode spriteNodeWithImageNamed:@"next"];
    agin.position = CGPointMake(self.size.width/2, self.size.height/2-40);
    agin.name = @"next";
    [self addChild:agin];
}

- (void)gameOver{
    
    [self addGradesNode];
    
    SKTexture *texture = [SKTexture textureWithImage:[UIImage imageNamed:@"paper_background"]];
    SKSpriteNode *background1 = [SKSpriteNode spriteNodeWithTexture:texture size:self.size];
    background1.position = CGPointMake(self.size.width/2, self.size.height/2);
    background1.zPosition = 0;
    [self addChild:background1];
    
    SKSpriteNode *alert = [SKSpriteNode spriteNodeWithImageNamed:@"paper_over"];
    alert.position = CGPointMake(self.size.width/2, self.size.height/2);
    [self addChild:alert];
    
    SKSpriteNode *menu = [SKSpriteNode spriteNodeWithImageNamed:@"btn_blue"];
    menu.position = CGPointMake(self.size.width/2, self.size.height/2+10);
    menu.name = @"menu";
    [self addChild:menu];
    
    SKSpriteNode *agin = [SKSpriteNode spriteNodeWithImageNamed:@"btn_green"];
    agin.position = CGPointMake(self.size.width/2, self.size.height/2-40);
    agin.name = @"agin";
    [self addChild:agin];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touche = [touches.allObjects firstObject];
    CGPoint location = [touche locationInNode:self];
    
    if (_isOver) {
        SKNode *node = [self nodeAtPoint:location];
        if ([node.name  isEqual: @"menu"]) {
            NSLog(@"-----------");
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"dismiss" object:nil];
        }
        if ([node.name isEqual:@"agin"]) {
            [self removeAllChildren];
            [self removeAllActions];
            [self didMoveToView:self.view];
            
        }
        if ([node.name isEqual:@"next"]) {
            [self removeAllChildren];
            [self removeAllActions];
            if (self.gameType<5) {
                self.gameType = _gameType++;
            }
            
            [self didMoveToView:self.view];
            
        }
        return;
    }else{
        [self runAction:_fashe];
        [self addBulletNodeBy:location];
    }

}

- (void)didBeginContact:(SKPhysicsContact *)contact{
    
    if (contact.bodyA.categoryBitMask == PhysicsBullet || contact.bodyB.categoryBitMask == PhysicsBullet) {
        
        [self runAction:_baofa];
        
        if (contact.bodyA.categoryBitMask == PhysicsPlanTwo || contact.bodyB.categoryBitMask == PhysicsPlanTwo) {
            
            [self changeGrades:-10];
            [self bulletDidCollideWithPlane:contact.bodyA.node and:contact.bodyB.node];
        }else if (contact.bodyA.categoryBitMask == PhysicsPlanThree || contact.bodyB.categoryBitMask == PhysicsPlanThree){
            [self changeGrades:3];
            [self bulletDidCollideWithPlane:contact.bodyA.node and:contact.bodyB.node];
        }else if (contact.bodyA.categoryBitMask == PhysicsPlanFour || contact.bodyB.categoryBitMask == PhysicsPlanFour){
            [self changeGrades:4];
            [self bulletDidCollideWithPlane:contact.bodyA.node and:contact.bodyB.node];
        }else if (contact.bodyA.categoryBitMask == PhysicsPlanFive || contact.bodyB.categoryBitMask == PhysicsPlanFive){
            [self changeGrades:5];
            [self bulletDidCollideWithPlane:contact.bodyA.node and:contact.bodyB.node];
        }else if (contact.bodyA.categoryBitMask == PhysicsPlanOne || contact.bodyB.categoryBitMask == PhysicsPlanOne){
            [self changeGrades:2];
            [self bulletDidCollideWithPlane:contact.bodyA.node and:contact.bodyB.node];
        }
    }
}
- (void)bulletDidCollideWithPlane:(SKNode *)planeNode and:(SKNode *)bulletNode{
    
    SKSpriteNode *peng = [SKSpriteNode spriteNodeWithImageNamed:@"baozha"];
    peng.position = planeNode.position;
    [self addChild:peng];
    
    SKAction *scale = [SKAction scaleBy:2 duration:0.3];
    SKAction *scaleDone = [SKAction removeFromParent];
    [peng runAction:[SKAction sequence:@[scale,scaleDone]]];
    
    [planeNode removeFromParent];
    [bulletNode removeFromParent];
}



-(void)update:(CFTimeInterval)currentTime {
    // Called before each frame is rendered
}

@end
